package com.xigege.nio.NIO案例;

import com.xigege.nio.bufferAndChannel.util.ByteBufferUtil;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 处理消息边界的nio多路复用
 * ex:
 *  发送此类消息，处理扩容以及消息边界（\n）的问题
 *   sc.write(StandardCharsets.UTF_8.encode("hello\nworldIamYourFatherSynchronous blocking, synchronous non blocking, synchronous multiplexing, asynchronous blocking (no such case), asynchronous non blocking\n"));
 *   sc.write(StandardCharsets.UTF_8.encode("hello\nworld"));
 */
public class NIOMultiplexingProcessMessageBoundariesServer {
    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                ByteBufferUtil.debugAll(target);
            }
        }
        source.compact();
    }

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if (selector.select(1000) == 0) {//没有事件发生
                System.out.println("服务器等待了1秒钟");
                continue;
            }

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生产了一个socketChannel: " + socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    // 在第三个参数中放入附件
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(8));
                }
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 获取附件, key.attach(Object)方法可以重新关联一个附件
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    int read = channel.read(buffer);
                    if (read < 0) {
                        key.cancel();
                    } else {
                        split(buffer);
                        // 老的buffer空间不够，进行扩容，并且把旧的buffer转移到新的buffer里面
                        if (buffer.limit() == buffer.position()){
                            ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                            newBuffer.put(buffer);
                            key.attach(newBuffer);
                        }
                    }
                }
                keyIterator.remove();
            }
        }
    }
}
